﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Text;

using XStudio.Core.Log;
using XStudio.Core.Ext.ConvertExtensions;
using Newtonsoft.Json;
using Core.API.Entity;

namespace Api.Providers
{
    public class TokenAuthAttribute : AuthorizeAttribute
    {

     
        protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
        {
            base.HandleUnauthorizedRequest(actionContext);

            if (actionContext.Response.StatusCode == HttpStatusCode.Unauthorized)
            {
                actionContext.Response.StatusCode = HttpStatusCode.OK;

                var res = ResponseApI.TokenError();

                string strRes = JsonConvert.SerializeObject(res);

                actionContext.Response.Content = new StringContent(strRes, Encoding.UTF8, "application/json");
            }
        }

        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            string token = "";
            try
            {
                token = actionContext.Request.Headers.GetValues("token").First();
            }
            catch
            {
                return false;
            }

            RespModel resp = new RespModel();
            if (!string.IsNullOrEmpty(token))
            {
            }
            else
            {
                System.Web.HttpContext.Current.Session["CurrentUser"] = null;
                return false;
            }
            //LoggerHelper.WriteInfo("token:" + token);
            return true;
        }

    }
}